package com.example.mytestdemo.customviewbook.two

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.example.mytestdemo.R

/**
 * @author tgw
 * @date 2023/2/8
 * @describe 折叠的view
 */
class PolytoPolyViewView2 @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {

    var bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.cat)
    val mMatrix: Matrix = Matrix()
    var sTransHeight = 100f
    var mFoldWidth = 0f
    var spiltNum = 8

    //j假设折叠后变为原来的0.8倍
    var mFactory = 0.8f


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mFoldWidth = (width / spiltNum).toFloat()
        var mFoldItemWidth = (width * 0.8 / spiltNum).toFloat()
        sTransHeight =
            Math.sqrt((mFoldWidth * mFoldWidth - mFoldItemWidth * mFoldItemWidth).toDouble())
                .toFloat()
        var src = floatArrayOf(
            mFoldWidth,
            0f,
            mFoldWidth * 2,
            0f,
            mFoldWidth * 2,
            bitmap.height.toFloat(),
            mFoldWidth,
            bitmap.height.toFloat()
        )
        var dst = floatArrayOf(
            mFoldItemWidth,
            sTransHeight,
            mFoldItemWidth * 2,
            0f,
            mFoldItemWidth * 2,
            bitmap.height.toFloat(),
            mFoldItemWidth,
            bitmap.height.toFloat() + sTransHeight
        )
        mMatrix.setPolyToPoly(src, 0, dst, 0, src.size shr 1)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.save()
        val rect = Rect(mFoldWidth.toInt(), 0, mFoldWidth.toInt() * 2, getHeight());
        canvas.setMatrix(mMatrix)
        canvas.clipRect(rect)
        canvas.drawBitmap(bitmap, 0f, 0f, null)
        canvas.restore()
    }


}